<template>
  <div class="main">
    <!-- 乘机人 -->
    <div class="air-column">
      <h2>乘机人</h2>
      <!-- 动态增减的乘机人数据校验完毕
      model:对象
      rules：饿了么允许直接在生成表单项的模板中直接针对当前 form-item 编写规则**数组** 
      prop：指定在 model 里面寻找数据的路径, 正常情况应该是 users[index].username
      
       -->
      <el-form class="member-info" :model="{ users }" ref="userform">
        <!-- 每个乘机人信息
        1、循环遍历users数组，里面的每个元素，就是每个乘机人信息
        2、数据绑定：循环遍历的每个元素，里面绑定相对应index的字段
         -->
        <div
          class="member-info-item"
          v-for="(item, index) in users"
          :key="index"
        >
          <el-form-item
            label="姓名"
            :prop="`users[${index}].username`"
            :rules="[
              {
                required: true,
                message: '请填写乘机人姓名',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              placeholder="请输入乘机人姓名"
              class="input-with-select"
              v-model="item.username"
            >
            </el-input>
          </el-form-item>

          <el-form-item
            label="身份证"
            :prop="`users[${index}].id`"
            :rules="[
              {
                required: true,
                message: '请填写乘机人姓名',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              placeholder="填写身份证号码"
              class="input-with-select"
              v-model="item.id"
            >
            </el-input>
          </el-form-item>

          <span class="delete-user" @click="handleDeleteUser(index)">-</span>
        </div>
      </el-form>

      <el-button class="add-member" type="primary" @click="handleAddUsers"
        >添加乘机人</el-button
      >
    </div>
    <!-- 保险 -->
    <div class="air-column">
      <h2>保险</h2>
      <div>
        <div class="insurance-item">
          <!-- <el-checkbox label="航空意外险：￥30/份×1  最高赔付260万" border>
          </el-checkbox> -->
          <el-checkbox-group v-model="insurances">
            <div
              class="insurance-item"
              v-for="(item, index) in data.insurances"
              :key="index"
            >
              <el-checkbox :label="item.id" border
                >{{ item.type }}：￥{{ item.price }}/份×{{
                  users.length
                }}最高赔付{{ item.compensation }}</el-checkbox
              >
            </div>
          </el-checkbox-group>
        </div>
      </div>
    </div>
    <!-- 是否申请发票 -->
    <div style="margin-bottom: 20px">
      <el-checkbox v-model="invoice">是否申请发票</el-checkbox>
    </div>
    <!-- 联系人信息 -->
    <div class="air-column">
      <h2>联系人</h2>
      <div class="contact">
        <el-form
          label-width="80px"
          :model="{ contactName, contactPhone, captcha }"
          :rules="contactRules"
          ref="contactForm"
        >
          <el-form-item label="姓名" prop="contactName">
            <el-input
              v-model="contactName"
              @focus="clearErrMsg('contactName')"
            ></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="contactPhone">
            <el-input
              placeholder="请输入内容"
              v-model="contactPhone"
              @focus="clearErrMsg('contactPhone')"
            >
              <template slot="append">
                <el-button @click="handleSendCaptcha">发送验证码</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="captcha">
            <el-input v-model="captcha" @focus="clearErrMsg('captcha')">
            </el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="warning"
          class="submit"
          @click="handleSubmit"
          v-if="$store.state.userstore.userInfo.token"
          >提交订单</el-button
        >
      </div>
    </div>
    <!-- 注册登录组件 -->
    <el-row
      type="flex"
      justify="center"
      align="middle"
      class="main"
      v-if="!$store.state.userstore.userInfo.token"
    >
      <div class="form-wrapper">
        <!-- 表单头部tab -->
        <el-row type="flex" justify="center" class="tabs">
          <span
            :class="{ active: currentTab === index }"
            v-for="(item, index) in [`登录`, `注册`]"
            :key="index"
            @click="handleChangeTab(index)"
          >
            {{ item }}
          </span>
        </el-row>

        <!-- 登录功能组件 -->
        <LoginForm v-if="currentTab == 0" />

        <!-- 注册功能组件 -->
        <RegisterForm v-if="currentTab == 1" @toLogin="currentTab = 0" />
      </div>
    </el-row>
  </div>
</template>

<script>
import LoginForm from "@/components/user/LoginForm";
import RegisterForm from "@/components/user/RegisterForm";
export default {
  components: {
    LoginForm,
    RegisterForm,
  },
  props: ["data"],
  data() {
    return {
      currentTab: 0,
      // 乘机人信息
      users: [
        {
          username: "橘子",
          id: "441734567893456189",
        },
      ],
      insurances: [], //   保险
      contactName: "面仔", //   联系人姓名
      contactPhone: "13456756777", //   联系人电话
      captcha: "", //验证码
      invoice: false, //   是否需要发票

      // 登录表单数据
      dataForm: {
        username: "13800138000", // 用户名
        password: "123456", // 密码
      },
      // 联系人校验规则、
      contactRules: {
        contactName: [
          {
            required: true,
            message: "请输入联系人",
            trigger: "blur",
          },
        ],
        contactPhone: [
          {
            required: true,
            message: "请输入联系人",
            trigger: "blur",
          },
        ],
        captcha: [
          {
            required: true,
            message: "请输入联系人",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    console.log(this.data);
  },
  watch: {
    // 监听乘机人变化和保险的变化
    // users() {
    //   // 计算总价格
    //   console.log("乘机人变化了");

    //   this.calcTotalPrice();
    // },
    users: {
      handler() {
        // 计算总价格
        console.log("乘机人变化了");
        this.calcTotalPrice();
      },
      // 在进入页面时让watch马上触发
      immediate: true,
    },

    insurances() {
      // 计算总价格
      console.log("保险变化了");
      this.calcTotalPrice();
    },
  },

  methods: {
    clearErrMsg(propName) {
      this.$refs.contactForm.clearValidate(propName);
    },
    // 计算总价：影响金额的因素：乘机人数量和保险
    calcTotalPrice() {
      let totalPrice = 0;
      // 1. 机票价格
      totalPrice += this.data.seat_infos.org_settle_price * this.users.length;
      // 2.保险价格
      // 2.1遍历insurances保险数组
      this.insurances.forEach((id, index) => {
        // 2.2遍历后台返回的机票信息的insurance保险数组---找到价格
        this.data.insurances.forEach((value) => {
          if (id == value.id) {
            totalPrice += value.price * this.users.length;
          }
        });
      });
      // 3。燃油费
      totalPrice += this.data.airport_tax_audlet * this.users.length;
      console.log(totalPrice);
      this.$emit("setTotalPrice", totalPrice, this.users.length);
    },

    handleSubmit() {
      // 提交订单发送请求前进行总的校验：2个表单校验
      // this.$refs.userform.validate().then((isValidUser) => {
      //   // 乘机人校验成功
      //   if (isValidUser) {
      //     // 进行联系人校验
      //     this.$refs.contactForm.validate().then((isValidContact) => {
      //       //  联系人校验成功、
      //       if (isValidContact) {
      //         // 进行请求处理
      //       }
      //     });
      //   }
      // });
      // Promise.all可以将多个Promise实例包装成一个新的Promise实例。同时，成功和失败的返回值是不同的，成功的时候返回的是一个结果数组，而失败的时候则返回最先被reject失败状态的值。
      // Promise.all 的用法---
      // 传入两个元素注册的数据
      // 所有res也是一个数组 上面promise的结果
      Promise.all([
        this.$refs.userform.validate(),
        this.$refs.contactForm.validate(),
      ]).then((res) => {
        if (res[0] && res[1]) {
          // 进行请求处理
          console.log("提交请求");
          this.$axios({
            method: "post",
            url: "/airorders",
            headers: {
              // 请求头传递token  前加 Bearer
              Authorization:
                "Bearer " + this.$store.state.userstore.userInfo.token,
            },
            data: {
              users: this.users,
              insurances: this.insurances,
              contactName: this.contactName, //   联系人姓名
              contactPhone: this.contactPhone, //   联系人电话
              captcha: this.captcha, //验证码
              invoice: this.invoice, //   是否需要发票
              seat_xid: this.$route.query.seat_xid,
              air: this.$route.query.id,
            },
          }).then((res) => {
            console.log(res);
            const { data, message } = res.data;

            if (message == "订单提交成功") {
              this.$message.success("订单提交成功");
              this.$router.push("/air/pay?id=" + data.air.id);
            }
          });
        }
      });
    },
    // 添加乘机人：往users数组里面添加push一个乘机人信息
    handleAddUsers() {
      this.users.push({
        username: "",
        id: "",
      });
    },
    // 删除乘机人,传入对应的index，删除对应index的元素
    handleDeleteUser(index) {
      this.users.splice(index, 1);
    },
    // 发送验证码
    handleSendCaptcha() {
      this.$axios({
        method: "post",
        url: "/captchas",
        data: {
          tel: this.contactPhone,
        },
      }).then((res) => {
        if (res.data.code) {
          this.$message.success(res.data.code);
        }
      });
    },

    //   输入框聚焦时清除规则
    chearRules(propName) {
      this.$refs.Form.clearValidate(propName);
    },

    handleChangeTab(index) {
      this.currentTab = index;
    },
  },
};
</script>

<style scoped lang="less">
.air-column {
  border-bottom: 1px #ddd dashed;
  padding-bottom: 20px;
  margin-bottom: 20px;
}

.air-column h2 {
  margin-bottom: 20px;
  font-size: 22px;
  font-weight: normal;
}

/deep/ .el-select .el-input {
  width: 130px;
}

.input-with-select {
  width: 590px;
}

.input-with-select /deep/ .el-input-group__prepend {
  background-color: #fff;
}
.member-info /deep/ .el-form-item {
  margin-bottom: 8px;
}

// 这里是每个乘机人的外容器
.member-info-item {
  border-bottom: 1px #eee dashed;
  padding-bottom: 20px;
  position: relative;

  &:first-child {
    .delete-user {
      display: none;
    }
  }
}

.add-member {
  margin-top: 20px;
}

.delete-user {
  display: block;
  background: #ddd;
  width: 16px;
  height: 16px;
  font-size: 14px;
  text-align: center;
  line-height: 16px;
  color: #fff;
  cursor: pointer;
  border-radius: 50px;
  position: absolute;
  right: -30px;
  top: 50%;
}

.insurance {
  > div {
    margin-top: 10px;
  }
}

.insurance-item {
  margin-bottom: 20px;
}

.contact {
  /deep/ .el-input {
    width: 50%;
  }
}

.submit {
  margin: 50px auto;
  display: block;
  width: 250px;
  height: 50px;
}
.main {
  height: 100%;
  margin: 0 auto;
  position: relative;

  .form-wrapper {
    width: 400px;
    margin: 0 auto;
    background: #fff;
    box-shadow: 2px 2px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .tabs {
      span {
        display: block;
        width: 50%;
        height: 50px;
        box-sizing: border-box;
        border-top: 2px #eee solid;
        background: #eee;
        line-height: 48px;
        text-align: center;
        cursor: pointer;
        color: #666;

        &.active {
          color: orange;
          border-top-color: orange;
          background: #fff;
          font-weight: bold;
        }
      }
    }
  }
}
</style>